package com.filetransfer.app.ui.upload;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.filetransfer.app.R;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.List;
public class LinksAdapter extends RecyclerView.Adapter<LinksAdapter.LinkViewHolder> {
    private static final Logger log = LoggerFactory.getLogger(LinksAdapter.class);
    private final List<URL> links;
    private final Context context;
    public LinksAdapter(Context context, List<URL> links) {
        this.context = context;
        this.links = links;
    }
    @NonNull
    @Override
    public LinkViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.link_item, parent, false);
        return new LinkViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull LinkViewHolder holder, int position) {
        URL link = links.get(position);
        holder.linkTextView.setText(link.toString());
        try {
            var l1 = link.toString()
                    .replace("%20", " ")
                    .replace("%28", "(")
                    .replace("%29", ")")
                    .split("/");
            var l2 = l1[l1.length - 1].split("\\.");
            var l3 = l2[0] + "." + l2[1];
            holder.linkTextView.setText(l3);
        } catch (Exception e) {
            log.error("Failed to parse URL", e);
        }
        holder.linkTextView.setOnClickListener(v -> {
            Toast.makeText(context, "启动浏览器下载", Toast.LENGTH_SHORT).show();
            var browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link.toString()));
            context.startActivity(browserIntent);
        });
        holder.copyButton.setOnClickListener(v -> {
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Link", link.toString());
            clipboard.setPrimaryClip(clip);
            Toast.makeText(context, "链接已复制到剪切板\n可直接分享下载链接", Toast.LENGTH_SHORT).show();
        });
    }
    @Override
    public int getItemCount() {
        return links.size();
    }
    static class LinkViewHolder extends RecyclerView.ViewHolder {
        TextView linkTextView;
        ImageView copyButton;
        public LinkViewHolder(@NonNull View itemView) {
            super(itemView);
            linkTextView = itemView.findViewById(R.id.linkTextView);
            copyButton = itemView.findViewById(R.id.copyButton);
        }
    }
}